package maven.demo6;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BinarySearchTest {
    public void sortCity() {
        List<String> cities = new ArrayList<String>();
        cities.add("上海");
        cities.add("广州");
        cities.add("广州");
        cities.add("北京");
        cities.add("天津");

        // indexOf 方法获取索引值
        int index1 = cities.indexOf("广州");
        // binarySearch 查找到索引值
        int index2 = Collections.binarySearch(cities, "广州");
        System.out.println("索引值（indexOf): " + index1);
        System.out.println("索引值（binarySearch): " + index2);
    }


    public void sortLarge() {
        int max = 1200000;
        List<String> cities = new ArrayList<String>();
        for(int i = 0; i < max;i++) {
            cities.add(String.valueOf(i));
        }
        // indexOf 方法获取索引值
        long start = System.nanoTime();
        int index1 = cities.indexOf(String.valueOf(max - 5));
        long mid = System.nanoTime();
        System.out.println(mid - start);
        System.out.println("索引值(indexOf)：" + index1);
        System.out.println("indexOf：" + cities.get(index1));


        // binarySearch 查找到索引值
        Collections.sort(cities);
        int index2 = Collections.binarySearch(cities, String.valueOf(max - 5));
//        int index2 = Collections.binarySearch(cities, (max - 5) + "");
        long end = System.nanoTime();
        System.out.println(end - mid);
        System.out.println("索引值(binarySearch)：" + index2);
        System.out.println("binarySearch：" + cities.get(index2));
        System.out.println("indexOf：" + cities.get(index1));
    }
}
